# 导包
import pymysql
from unit_tools.handle_data.configParse import ConfigParse
from unit_tools.log_util.recordlog import logs

conf = ConfigParse()

class ConnectMysql:

    def __init__(self):
        self.conf = {
            'host': conf.get_mysql_conf('host'),
            'port': int(conf.get_mysql_conf('port')),
            'user': conf.get_mysql_conf('user'),
            'password': conf.get_mysql_conf('password'),
            'database': conf.get_mysql_conf('database')
        }
        try:
            self.conn = pymysql.connect(**self.conf)
            self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            logs.info(f'成功连接到数据库：数据库ip：{self.conf.get("host")}')
        except Exception as e:
            logs.error(f'连接数据库失败：原因：{e}')

    def close(self):
        if self.conn and self.cursor:
            self.conn.close()
            self.cursor.close()
        return True

    def query(self, sql, fetchall=False):

        try:
            self.cursor.execute(sql)
            self.conn.commit()
            if fetchall:
                res = self.cursor.fetchall()
            else:
                res = self.cursor.fetchone()
            return res
        except Exception as e:
            logs.error(f'查询数据库内容出现异常：{e}')
        finally:
            self.close()

    def delete(self, sql):

        try:
            self.cursor.execute(sql)
            self.conn.commit()
            logs.info('数据库数据删除成功！')
        except Exception as e:
            logs.error(f'删除数据库数据出现异常：{e}')
        finally:
            self.close()


if __name__ == '__main__':
    con = ConnectMysql()
    sql = "select * from test where age = 40"
    res = con.query(sql)
    print(res)